import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Table, Tag, Space, Button, Input, Badge, Progress, Statistic, message } from 'antd';
import ElevatorDetailModal from './components/ElevatorDetailModal';
import { 
  SearchOutlined, 
  ReloadOutlined, 
  EyeOutlined, 
  SettingOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  PauseOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import ElevatorStatusCard from './components/ElevatorStatusCard';
import ElevatorControlPanel from './components/ElevatorControlPanel';

const { Search } = Input;

// 电梯数据接口
interface ElevatorData {
  id: string;
  name: string;
  location: string;
  status: 'running' | 'idle' | 'maintenance' | 'fault';
  direction: 'up' | 'down' | 'idle';
  currentFloor: number;
  targetFloor?: number;
  load: number;
  maxLoad: number;
  minFloor: number;
  maxFloor: number;
  emergencyStop: boolean;
  maintenanceMode: boolean;
  lastUpdate: string;
}

// 模拟电梯数据
const mockElevatorData: ElevatorData[] = [
  {
    id: 'ELV001',
    name: '1号电梯',
    location: 'A座',
    status: 'running',
    currentFloor: 5,
    targetFloor: 8,
    direction: 'up',
    load: 450,
    maxLoad: 1000,
    minFloor: 1,
    maxFloor: 20,
    emergencyStop: false,
    maintenanceMode: false,
    lastUpdate: '2024-01-20 14:30:25'
  },
  {
    id: 'ELV002',
    name: '2号电梯',
    location: 'A座',
    status: 'running',
    currentFloor: 12,
    targetFloor: 6,
    direction: 'down',
    load: 680,
    maxLoad: 1000,
    minFloor: 1,
    maxFloor: 20,
    emergencyStop: false,
    maintenanceMode: false,
    lastUpdate: '2024-01-20 14:29:15'
  },
  {
    id: 'ELV003',
    name: '3号电梯',
    location: 'B座',
    status: 'fault',
    currentFloor: 8,
    direction: 'idle',
    load: 0,
    maxLoad: 1000,
    minFloor: 1,
    maxFloor: 18,
    emergencyStop: true,
    maintenanceMode: false,
    lastUpdate: '2024-01-20 13:45:30'
  },
  {
    id: 'ELV004',
    name: '4号电梯',
    location: 'B座',
    status: 'maintenance',
    currentFloor: 1,
    direction: 'idle',
    load: 0,
    maxLoad: 1000,
    minFloor: 1,
    maxFloor: 18,
    emergencyStop: false,
    maintenanceMode: true,
    lastUpdate: '2024-01-20 10:00:00'
  },
  {
    id: 'ELV005',
    name: '5号电梯',
    location: 'C座',
    status: 'idle',
    currentFloor: 3,
    direction: 'idle',
    load: 320,
    maxLoad: 800,
    minFloor: 1,
    maxFloor: 15,
    emergencyStop: false,
    maintenanceMode: false,
    lastUpdate: '2024-01-20 14:28:45'
  },
  {
    id: 'ELV006',
    name: '6号电梯',
    location: 'C座',
    status: 'idle',
    currentFloor: 1,
    direction: 'idle',
    load: 0,
    maxLoad: 800,
    minFloor: 1,
    maxFloor: 15,
    emergencyStop: false,
    maintenanceMode: false,
    lastUpdate: '2024-01-20 14:25:10'
  }
];

const ElevatorSystem: React.FC = () => {
  const [elevatorData, setElevatorData] = useState<ElevatorData[]>(mockElevatorData);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedElevator, setSelectedElevator] = useState<ElevatorData | null>(null);
  const [controlPanelVisible, setControlPanelVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);

  // 状态统计
  const getStatusStatistics = () => {
    const total = elevatorData.length;
    const running = elevatorData.filter(item => item.status === 'running').length;
    const idle = elevatorData.filter(item => item.status === 'idle').length;
    const fault = elevatorData.filter(item => item.status === 'fault').length;
    const maintenance = elevatorData.filter(item => item.status === 'maintenance').length;
    
    return { total, running, idle, fault, maintenance };
  };

  const statistics = getStatusStatistics();

  // 状态标签渲染
  const renderStatus = (status: string) => {
    const statusMap = {
      running: { color: 'green', text: '运行中' },
      idle: { color: 'blue', text: '空闲' },
      fault: { color: 'red', text: '故障' },
      maintenance: { color: 'orange', text: '维护中' }
    };
    
    const config = statusMap[status as keyof typeof statusMap];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 方向图标渲染
  const renderDirection = (direction: string) => {
    const directionMap = {
      up: { icon: <ArrowUpOutlined />, color: '#52c41a', text: '上行' },
      down: { icon: <ArrowDownOutlined />, color: '#1890ff', text: '下行' },
      idle: { icon: <PauseOutlined />, color: '#666', text: '停止' }
    };
    
    const config = directionMap[direction as keyof typeof directionMap];
    return (
      <span style={{ color: config.color }}>
        {config.icon} {config.text}
      </span>
    );
  };

  // 负载进度条渲染
  const renderLoadProgress = (record: ElevatorData) => {
    const percentage = (record.load / record.maxLoad) * 100;
    let color = '#52c41a';
    if (percentage >= 90) color = '#ff4d4f';
    else if (percentage >= 70) color = '#faad14';
    
    return (
      <div>
        <div style={{ marginBottom: 4 }}>
          {record.load}kg / {record.maxLoad}kg
        </div>
        <Progress 
          percent={percentage} 
          size="small" 
          strokeColor={color}
          format={() => `${Math.round(percentage)}%`}
        />
      </div>
    );
  };

  // 表格列配置
  const columns: ColumnsType<ElevatorData> = [
    {
      title: '电梯名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: (text, record) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{text}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.id}</div>
        </div>
      ),
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: renderStatus,
    },
    {
      title: '当前楼层',
      dataIndex: 'currentFloor',
      key: 'currentFloor',
      width: 100,
      render: (floor, record) => (
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '18px', fontWeight: 'bold' }}>{floor}F</div>
          {record.targetFloor && record.direction !== 'idle' && (
            <div style={{ fontSize: '12px', color: '#666' }}>
              → {record.targetFloor}F
            </div>
          )}
        </div>
      ),
    },
    {
      title: '运行方向',
      dataIndex: 'direction',
      key: 'direction',
      width: 100,
      render: renderDirection,
    },
    {
      title: '负载情况',
      key: 'load',
      width: 150,
      render: (_, record) => renderLoadProgress(record),
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdate',
      key: 'lastUpdate',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleViewElevator(record)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<SettingOutlined />} 
            size="small"
            onClick={() => handleControlElevator(record)}
            disabled={record.status === 'fault'}
          >
            控制
          </Button>
        </Space>
      ),
    },
  ];

  // 处理查看电梯
  const handleViewElevator = (record: ElevatorData) => {
    setSelectedElevator(record);
    setDetailVisible(true);
  };

  // 处理控制电梯
  const handleControlElevator = (record: ElevatorData) => {
    setSelectedElevator(record);
    setControlPanelVisible(true);
  };

  // 处理电梯控制操作
  const handleElevatorControl = async (action: string, params?: any) => {
    if (!selectedElevator) return;
    
    console.log('电梯控制操作:', action, params);
    
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        // 更新电梯状态
        setElevatorData(prev => prev.map(elevator => {
          if (elevator.id === selectedElevator.id) {
            const updated = { ...elevator };
            
            switch (action) {
              case 'goto_floor':
                updated.targetFloor = params.floor;
                updated.direction = params.floor > elevator.currentFloor ? 'up' : 'down';
                updated.status = 'running';
                break;
              case 'emergency_stop':
                updated.emergencyStop = true;
                updated.direction = 'idle';
                updated.status = 'fault';
                break;
              case 'maintenance_mode':
                updated.maintenanceMode = params.enabled;
                updated.status = params.enabled ? 'maintenance' : 'idle';
                break;
              case 'start':
                updated.status = 'idle';
                updated.emergencyStop = false;
                break;
              case 'stop':
                updated.status = 'idle';
                updated.direction = 'idle';
                break;
            }
            
            updated.lastUpdate = new Date().toLocaleString();
            return updated;
          }
          return elevator;
        }));
        
        resolve(true);
      }, 1000);
    });
  };

  // 刷新数据
  const handleRefresh = () => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      setLoading(false);
      message.success('数据已刷新');
    }, 1000);
  };

  // 过滤数据
  const filteredData = elevatorData.filter(item => {
    const matchSearch = item.name.toLowerCase().includes(searchText.toLowerCase()) ||
                       item.id.toLowerCase().includes(searchText.toLowerCase()) ||
                       item.location.toLowerCase().includes(searchText.toLowerCase());
    return matchSearch;
  });

  return (
    <div style={{ padding: '0' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="电梯总数"
              value={statistics.total}
              prefix={<Badge status="processing" />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="运行中"
              value={statistics.running}
              valueStyle={{ color: '#3f8600' }}
              prefix={<Badge status="success" />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="故障"
              value={statistics.fault}
              valueStyle={{ color: '#cf1322' }}
              prefix={<Badge status="error" />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="维护中"
              value={statistics.maintenance}
              valueStyle={{ color: '#d48806' }}
              prefix={<Badge status="warning" />}
            />
          </Card>
        </Col>
      </Row>

      {/* 电梯状态卡片 */}
      <Card title="电梯状态总览" style={{ marginBottom: 24 }}>
        <Row gutter={16}>
          {elevatorData.map(elevator => (
            <Col span={8} key={elevator.id} style={{ marginBottom: 16 }}>
              <ElevatorStatusCard
                elevator={elevator}
                onClick={() => handleControlElevator(elevator)}
              />
            </Col>
          ))}
        </Row>
      </Card>

      {/* 电梯列表 */}
      <Card 
        title="电梯详细列表"
        extra={
          <Space>
            <Search
              placeholder="搜索电梯名称、ID或位置"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 250 }}
              allowClear
            />
            <Button 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh}
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 电梯控制面板 */}
      {selectedElevator && (
        <ElevatorControlPanel
          visible={controlPanelVisible}
          onClose={() => {
            setControlPanelVisible(false);
            setSelectedElevator(null);
          }}
          elevator={selectedElevator}
          onControl={handleElevatorControl}
        />
      )}

      {/* 电梯详情弹窗 */}
      {selectedElevator && (
        <ElevatorDetailModal
          visible={detailVisible}
          onClose={() => setDetailVisible(false)}
          elevator={selectedElevator}
        />
      )}
    </div>
  );
};

export default ElevatorSystem;